<?php

namespace app\api\controller;

use app\admin\model\Order as AdminModelOrder;
use app\admin\model\ServersUser;
use app\admin\model\SystemConfig;
use app\api\model\Goods;
use app\api\model\GoodsProduct;
use app\api\model\Order as ModelOrder;
use app\api\model\OrderItem;
use app\api\model\ServerUser;
use app\api\model\ServiceTime;
use app\api\model\SuserItem;
use app\api\model\User;
use app\api\model\UserAddress;
use app\common\controller\ApiController;
use think\App;
use think\facade\Db;
use think\facade\Env;
use WeChat\Pay;
use \app\admin\traits\Curd;
use app\api\model\AfterOrder;
use app\api\model\AfterOrderItem;
use app\api\model\AttachOrder;
use app\api\model\Finance;
use app\api\model\OrderRecord;
use app\Request;

class Order extends ApiController
{

    protected $noNeedLogin = [];
    protected $mustLogin = [];

    protected $wechat_config = [];
    // protected $allowModifyFileds = ['username', 'sort', 'status_text'];

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        $this->wechat_config = [
            // 'token'          => 'test',
            'appid' => Env::get('pay.appid'),
            'appsecret' => '',
            'encodingaeskey' => '',
            // 配置商户支付参数（可选，在使用支付功能时需要）
            'mch_id' => Env::get('pay.mchid'),
            'mch_key' => Env::get('pay.apikey'),
            // 配置商户支付双向证书目录（可选，在使用退款|打款|红包时需要）
            'ssl_key' => root_path() . '/cert/apiclient_key.pem',
            'ssl_cer' => root_path() . '/cert/apiclient_cert.pem',
            // 缓存目录配置（可选，需拥有读写权限）
            'cache_path' => '',
        ];
        parent::__construct($app);
        $this->model = new ModelOrder();
    }

    /**
     * 下单预约
     */
    public function create_order()
    {
        $param = $this->request->param();
        if (empty($param['service_gid'])) {
            $this->error('未找到指定服务');
        }
        if (empty($param['service_time'])) {
            $this->error('请选择预约时间');
        }
        if (empty($param['address_id'])) {
            $this->error('请选择地址');
        }
        if (empty($param['service_good_price'])) {
            $this->error('产品价格不能为空');
        }
        if (empty($param['spec_id'])) {
            $this->error('请选择规格');
        }
        //商品规格
        $spec = Db::name("service_duration")->where("id",$param["spec_id"])->find();
        
        $total_price = $spec["price"];
        //is_use_coupon 是否使用优惠券
        if($param['is_use_coupon'] == 2){
            if (empty($param['coupon_id'])) {
                $this->error('优惠券id不能为空');
            }
            $coupon_user = Db::name('coupon_user')->where('uid',$this->uid)->where('coupon_id',$param['coupon_id'])->where("status",1)->find();
            if(empty($coupon_user)){
                $this->error('优惠券不存在');
            }else{
                //查询优惠券金额  less_amount
                $coupon = Db::name('coupon')->where('id',$coupon_user['coupon_id'])->find();
                if($coupon['endtime'] <= date('Y-m-d H:i:s',time())){
                    $this->error('优惠券已过期');
                }
                $payable_money = bcsub($total_price, $coupon['less_amount'], 2);
                $less_amount = $coupon['less_amount'];
            }
        }else{
            $payable_money = $spec["price"];
            $less_amount = 0;
        }
        $order_no = date('Ymd') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . $this->uid;
        $data = [
            'service_gid'=>$param['service_gid'],
            'service_time'=>$param['service_time'],
            'address_id'=>$param['address_id'],
            'service_good_price'=>$param['service_good_price'],
            'spec_id'=>$param['spec_id'],
            'type'=>1,
            'uid'=>$this->uid,
            'order_no'=>$order_no,
            'create_time'=>time(),
            'payable_money'=>$payable_money,//应付金额
            'total_price'=>$total_price,//总价
            "remark"=>$param['remark'],
            "is_use_coupon"=>$param["is_use_coupon"],
            "coupon_id"=>$param["coupon_id"],
            "coupon_money"=>$less_amount
        ];
        Db::startTrans();
        try {
            Db::name('order')->insert($data); 
            $orderId = Db::name('order')->getLastInsID();
            //减少产品规格库存
            //{"服务人数":["2人","4人"],"服务时长":["1小时","3小时"]}
            //{"服务人数":"2人","服务时长":"3小时"}
            Db::name("service_duration")->where("id",$param['spec_id'])->dec("stock")->update();
            //存储规格
            $spec_data = [
                "oid"=>$orderId,
                "spec_id"=>$spec["id"],
                "service_gid"=>$spec["service_gid"],
                "specs_list"=>$spec["specs_list"],
                "price"=>$spec["price"],
                "stock"=>$spec["stock"],
                "create_time"=>time(),
            ];
            Db::name("order_item")->insert($spec_data);
        } catch (\Throwable $th) {
            Db::rollback();
            $this->error('下单失败，请稍后重试');
        }
        Db::commit();
        $this->success('下单成功，请支付', ['order_no' => $order_no, 'orderId'=>$orderId]);
    }

    
    /**
     * 订单支付
     */
    public function order_payment()
    {
        $param = $this->request->param();
        if (empty($param['order_no'])) {
            $this->error('未找到指定订单');
        }
        $orderData = ModelOrder::where('order_no', $param['order_no'])->where('status', 1)->where('uid', $this->uid)->find();
        if (empty($orderData)) {
            $this->error('未找到指定订单');
        }
        $orderData = $orderData->toArray();
        //生成新的支付订单号
        $random_data = $orderData['id'].rand(1,99999).substr(time(),1,2);
        $new_order_no = $param['order_no'].$random_data;
        //判断金额是否为0
        if($orderData['payable_money'] == 0){
                if($orderData['status'] == 1){
                    if($orderData['is_use_coupon'] == 2){
                         //修改优惠券状态
                         Db::name('coupon_user')->where('coupon_id',$orderData['coupon_id'])->where('uid',$orderData['uid'])->update(['status'=>2,'use_time'=>date('Y-m-d H:i:s',time())]);
                    }
                    $up_data = [
                        "pay_time" => time(),
                        'status'=>2,
                        'paidin_money'=>$orderData['payable_money']
                    ];
                    Db::name('order')->where('order_no', $param['order_no'])->where('status', 1)->update($up_data);
                    $order_record = Db::name('order_record')->where('oid',$orderData['id'])->find();
                    if(empty($order_record)){
                        Db::name('order_record')->insert(['oid'=>$orderData['id'],'order_no'=>$param['order_no'],'random_data'=>$random_data,'new_order_no'=>$new_order_no]);
                    }else{
                        Db::name('order_record')->where('oid',$orderData['id'])->update(['order_no'=>$param['order_no'],'random_data'=>$random_data,'new_order_no'=>$new_order_no]);
                    }
                    $this->success('支付成功');
                 }else{
                    $this->error('支付失败');
                 }
        }else{
            $openid = User::where('id', $orderData['uid'])->value("wx_openid");
            $http = is_https() ? 'https' : 'http';
            $notify = $http . '://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER["SERVER_PORT"] . '/api/notify/wechat_notify';
            $wechat = new Pay($this->wechat_config);

            $options = [
                'body' => '订单支付',
                'out_trade_no' => $new_order_no,
                'attach'=>1,//1、正常单第一次支付
                'total_fee' => bcmul($orderData['payable_money'], 100),
                'openid' => $openid,
                'trade_type' => 'JSAPI',
                'notify_url' => $notify,
                'spbill_create_ip' => '127.0.0.1',
            ];
            $result = $wechat->createOrder($options);
            if ($result['return_code'] == "SUCCESS" && $result['return_msg'] == 'OK') {
                $ret = $wechat->createParamsForJsApi($result['prepay_id']);
                $order_record = Db::name('order_record')->where('oid',$orderData['id'])->find();
                if(empty($order_record)){
                    Db::name('order_record')->insert(['oid'=>$orderData['id'],'order_no'=>$param['order_no'],'random_data'=>$random_data,'new_order_no'=>$new_order_no]);
                }else{
                    Db::name('order_record')->where('oid',$orderData['id'])->update(['order_no'=>$param['order_no'],'random_data'=>$random_data,'new_order_no'=>$new_order_no]);
                }
                $this->success('ok', $ret);
            } else {
                $this->error("支付失败");
            }
        }
    }

    /**
     * 退款  status = 2的时候可以退款
     */
    public function cancle_order(ModelOrder $order)
    {
        $param = $this->request->param();
        if (empty($param['order_no'])) {
            $this->error('未找到指定订单');
        }
        $ret = $order->where('order_no', $param['order_no'])->where('status', 2)->where('uid', $this->uid)->find();
        if (empty($ret)) {
            $this->error('当前订单不能退款');
        }
        if ($ret['payable_money'] == 0) {
            $order->where('id', $ret['id'])->update(['status' => 3]);
            Db::name('art_performance')->where('id',$ret['apid'])->inc('num',$ret['num'])->update();
            $this->success('退款成功');
        } else {//需要退款
            $result = $this->wxchat_back($ret['transaction_id'], $ret['order_no'], $ret['payable_money'] * 100);
            if($result['code'] == 1){
                $order->where('id', $ret['id'])->update(['status' => 3]);
                Db::name('art_performance')->where('id',$ret['apid'])->inc('num',$ret['num'])->update();
                $this->success('退款成功', '');
            } else {
                $order->where('id', $ret['id'])->update(['fail_msg' => $result['msg']]);
                $this->error('退款失败');
            }
        }
    }

    //取消订单
    public function cancellation_of_order(ModelOrder $order){
        $param = $this->request->param();
        if (empty($param['oid'])) {
            $this->error('未找到指定订单');
        }
        $ret = $order->where('id', $param['oid'])->where('status', 1)->where('uid', $this->uid)->find();
        if (empty($ret)) {
            $this->error('当前订单不能取消');
        }
        $order->where('id', $param['oid'])->update(["status"=>8]);
     //   $order->destroy($param['oid']);
        $this->success('取消成功');
    }

    public function wxchat_back($transaction_id, $out_refund_no, $money)
    {
        try {
            $wechat = \WeChat\Pay::instance($this->wechat_config);
             $options = [
                'transaction_id' => $transaction_id,
                'out_refund_no'  => $out_refund_no,
                'total_fee'      => $money,
                'refund_fee'     => $money,
            ];
            $result = $wechat->createRefund($options);
            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                return ['code' =>1, 'data' => $result];
            } else{
                return ['code'=>0, 'msg'=>$result['err_code_des']];
            }
        } catch (\Throwable $th) {
            return ['code'=>0, 'msg'=>$th->getMessage()];
        }
    }


    /**
     * 订单列表
     */
    public function order_list(ModelOrder $order)
    {
        $param = $this->request->param();
        $status = empty($param['type'])?0:$param['type'];
        $where = [['uid', '=', $this->uid]];
        if ($status == 1) {//待付款
            $where = [
                ['uid', '=', $this->uid],
                ['status', '=', 1]
            ];
        }
        if ($status == 2) {//待服务
            $where = [
                ['uid', '=', $this->uid],
                ['status', '=', 2]
            ];
        }
        if ($status == 3) {//待确认
            $where = [
                ['uid', '=', $this->uid],
                ['status', '=', 3]
            ];
        }
        if ($status == 4) {//待评价
            $where = [
                ['uid', '=', $this->uid],
                ['status', '=', 4]
            ];
        }
        if ($status == 5) {//退款
            $where = [
                ['uid', '=', $this->uid],
                ['is_order_refund', 'in', "1,2,3"]
            ];
        }
        if ($status == 0) {//全部
            $where = [
                ['uid', '=', $this->uid],
                ['status', 'in', '1,2,3,4,5,6,7,8']
            ];
        }
        $list = $order->where($where)->order('create_time', 'desc')
            ->field("id,order_no,service_time,status,type,payable_money,paidin_money,service_gid,is_complete_service,is_order_refund,spec_id,reason_for_rejection")
            ->paginate(10)->each(function($item){
                $service_goods = Db::name('service_goods')->where('id',$item['service_gid'])->field('id,title,zhu_img')->find();
                $service_duration = Db::name('service_duration')->where('id',$item['spec_id'])->find();
                if(empty($service_duration)){
                    $order_item = Db::name("order_item")->where("oid",$item["id"])->find();
                    $service_goods["price"] = $order_item["price"];
                }else{
                    $service_goods["price"] = $service_duration["price"];
                }
                $item['service_goods'] = $service_goods;
                //查询是否有差价订单
                $flag = Db::name("order_price_difference")->where("oid",$item["id"])->where("status",0)->find();
                if(empty($flag)){
                    $item['is_check'] = false;
                }else{
                    $item['is_check'] = $flag["sub_order_no"];
                }

                //查询是否已评价
                $order_evaluate = Db::name("order_evaluate")->where("oid",$item['id'])->find();
                if(empty($order_evaluate)){
                    $item['is_order_evaluate'] = false;
                }else{
                    $item['is_order_evaluate'] = true;
                }

                return $item;
            });
        $this->success('查询成功', $list);
       
    }

    /**
     * 订单详情
     */
    public function order_detail()
    {
        $param = $this->request->param();
        if (empty($param['order_id'])) {
            $this->error('未找到指定订单');
        }
        $ret = Db::name("order")->where('id', $param['order_id'])->where('uid', $this->uid)->find();
        if (empty($ret)) {
            $this->error('订单不存在');
        }
        //查询是否已评价
        $order_evaluate = Db::name("order_evaluate")->where("oid",$ret['id'])->find();
        if(empty($order_evaluate)){
            $ret['is_order_evaluate'] = false;
        }else{
            $ret['is_order_evaluate'] = true;
        }

         //查询是否有差价订单
         $flag = Db::name("order_price_difference")->where("oid",$ret["id"])->find();
         if(empty($flag)){
             $ret['is_check'] = false;
         }else{
             $ret['is_check'] = $flag;
         }

        $service_duration = Db::name('service_duration')->where('id',$ret['spec_id'])->find();
        $service_goods = Db::name('service_goods')->where('id',$ret['service_gid'])->field("id,title,zhu_img")->find();
        if(empty($service_duration)){
            $order_item = Db::name("order_item")->where("oid",$ret["id"])->find();
            $sku_attribute_list = json_decode($order_item["specs_list"],true);
            $service_goods["price"] = $order_item["price"];
        }else{
            $sku_attribute_list = json_decode($service_duration["specs_list"],true);
            $service_goods["price"] = $service_duration["price"];
        }
        $adderss = Db::name("address")->where("id",$ret["address_id"])->find();
        $ret['adderss'] = $adderss;
        $ret['spec_data'] = $sku_attribute_list;
        $ret['service_goods'] = $service_goods;
        $this->success('查询成功', $ret);
    }

    //订单评价
    public function order_evaluate(){
        $param = $this->request->param();
        if (empty($param['order_id'])) {
            $this->error('未找到指定订单');
        }
        if (empty($param['star_rating'])) {
            $this->error('星级不能为空');
        }
        if (empty($param['content'])) {
            $this->error('评价内容不能为空');
        }
        $order = Db::name("order")->where("id",$param['order_id'])->field("service_gid")->find();
        if(empty($order)){
            $this->error('订单不存在');
        }
        $data = [
            "uid"=>$this->uid,
            "oid"=>$param['order_id'],
            "service_good_id"=>$order["service_gid"],
            "star_rating"=>$param['star_rating'],
            "content"=>$param['content'],
            "create_time"=>time(),
        ];
        Db::name("order_evaluate")->insert($data);
        Db::name("order")->where("id",$param["order_id"])->update(["status"=>7]);
        $this->success('评论成功');
    }

    //技师数据统计
    public function data_statistics(){
        $param = $this->request->param();
        if (empty($param['sid'])) {
            $this->error('未找到指定技师');
        }
        $s = strtotime(date('Y-m-d').'00:00:00');
        $l = strtotime(date('Y-m-d').'23:59:59');
        //今日预约
        $appointment_today = Db::name("order_scanning_code")->alias("os")
                        ->join("order o","o.id = os.oid")
                        ->where('os.service_user_id', $param['sid'])
                        ->where("os.is_cancel",0)
                        ->where("o.status","in","2,3")
                        ->whereTime('os.create_time', 'between', [$s, $l])
                        ->count();
        $appointment_today_wc = Db::name("order_scanning_code")->alias("os")
                        ->join("order o","o.id = os.oid")
                        ->where('os.service_user_id', $param['sid'])
                        ->where("os.update_time",">",0)
                        ->where("o.status","in","4,7")
                        ->whereTime('os.create_time', 'between', [$s, $l])
                        ->count();
        $total_appointment_today = bcadd($appointment_today,$appointment_today_wc);
        //总预约
        $zong_order_appointment = Db::name("order_scanning_code")->where('service_user_id', $param['sid'])->where("is_cancel",0)->count();
        //待服务订单 
        $in_service = Db::name("order_scanning_code")->alias("os")
                    ->join("order o","o.id = os.oid")
                    ->where('os.service_user_id', $param['sid'])
                    ->where("o.status",2)
                    ->where("os.is_cancel",0)
                    ->count();
        //待确认订单
        $tobe_confirmed = Db::name("order_scanning_code")->alias("os")
                        ->join("order o","o.id = os.oid")
                        ->where('os.service_user_id', $param['sid'])
                        ->where("o.status",3)
                        ->where("os.is_cancel",0)
                        ->count();
        //已完成订单
        $completed = Db::name("order_scanning_code")->alias("os")
                  ->join("order o","o.id = os.oid")
                  ->where('os.service_user_id', $param['sid'])
                  ->where("os.update_time",">",0)
                  ->where("o.status","in","4,7")
                  ->where("os.is_cancel",0)
                  ->count();
        $ret = [
            "appointment_today"=>$total_appointment_today,
            "zong_order_appointment"=>$zong_order_appointment,
            "in_service"=>$in_service,
            "tobe_confirmed"=>$tobe_confirmed,
            "completed"=>$completed,
        ];
        $this->success('查询成功', $ret);
    }

    //技师登录
    public function technician_login(){
        $param = $this->request->param();
        if (empty($param['phone'])) {
            $this->error('账号不能为空');
        }
        if (empty($param['password'])) {
            $this->error('密码不能为空');
        }
        $flag = Db::name("service_technician")->where("phone",$param['phone'])->find();
        if(empty($flag)){
            $this->error('账号不存在');
        }
        if(md5($param['password']) != $flag["password"]){
            $this->error('密码不正确');
        }
        if(empty($flag["uid"])){
            Db::name("service_technician")->where("phone",$param['phone'])->update(["uid"=>$this->uid]);
        }
        $this->success('登录成功',$flag);
    }

    //技师端平台取消订单
    public function teach_cancel_order(){
        $param = $this->request->param();
        if (empty($param['sid'])) {
            $this->error('技师id不能为空');
        }
     
        $where = [
            ['os.is_cancel', '=', 1]
        ];
        $order_scanning_code = Db::name("order_scanning_code")
                            ->alias("os")
                            ->join("order o","o.id = os.oid")
                            ->where("os.service_user_id",$param["sid"])
                            //->where("os.is_confirm",$osis_confirm)
                            ->where($where)
                            // ->where("os.status",$osstatus)
                            // ->where("o.status",$ostatus)
                            ->field("os.id as osid,os.status as osstatus,os.service_user_id,o.id as oid,o.order_no,o.service_time,o.status as ostatus,o.service_gid,o.spec_id,o.address_id,o.create_time,o.type,os.is_cancel")
                            ->paginate(10)->each(function($item){
                                $service_duration = Db::name('service_duration')->where('id',$item['spec_id'])->find();
                                $service_goods = Db::name('service_goods')->where('id',$item['service_gid'])->field("id,title,zhu_img")->find();
                                if(!empty($service_duration)){
                                    $sku_attribute_list = json_decode($service_duration["specs_list"],true);
                                    $item['spec_data'] = $sku_attribute_list;
                                    $service_goods["price"] = $service_duration["price"];
                                }else{
                                    $order_item = Db::name("order_item")->where("oid",$item["oid"])->find();
                                    $sku_attribute_list = json_decode($order_item["specs_list"],true);
                                    $item['spec_data'] = $sku_attribute_list;
                                    $service_goods["price"] = $order_item["price"];
                                }
                                $item['service_goods'] = $service_goods;
                                $adderss = Db::name("address")->where("id",$item["address_id"])->find();
                                if(!empty($adderss)){
                                    $item['adderss'] = $adderss;
                                }else{
                                    $item['adderss'] = "";
                                }
                                //判断是否有差价订单
                                $flag = Db::name("order_price_difference")->where("oid",$item["oid"])->find();
                                if(empty($flag)){
                                    $item['is_check'] = false;
                                }else{
                                    $item['is_check'] = true;
                                }

                                //判断是否已确认
                                $flag_qew = Db::name("order_scanning_code")->where("oid",$item["oid"])->where("is_confirm",1)->find();
                                if(empty($flag_qew)){
                                    $item['is_confirm'] = false;
                                }else{
                                    $item['is_confirm'] = true;
                                }
                                return $item;
                            });
        $this->success('获取成功',$order_scanning_code);      
    }

    //技师服务订单
    public function in_service_order(){
        $param = $this->request->param();
        if (empty($param['sid'])) {
            $this->error('技师id不能为空');
        }
        //1 待服务  2待确认  3已完成
        if (empty($param['type'])) {
            $this->error('类型不能为空');
        }
        if($param['type'] == 1){
            $where = [
                ['os.status', '=', 0],
                ['o.status', '=', 2],
                ['os.is_cancel', '=', 0],
            ];
            $whereOr = ["is_sso"=>1];
        }elseif($param['type'] == 2){
            $where = [
                ['os.status', '=', 1],
                ['o.status', '=', 3],
                ['os.is_cancel', '=', 0],
            ];
            $whereOr = ["is_sso"=>1];
        }elseif($param['type'] == 3){
            $where = [
                ['os.status', '=', 1],
                ['o.status', 'in', "4,7"],
                ['os.is_cancel', '=', 0],
            ];
            $whereOr = ["is_sso"=>1];
        }elseif($param['type'] == 4){
            $where = ["is_sso"=>1];
            $whereOr = [
                ['os.is_cancel', '=', 1],
                ['o.status', 'in', "5"],
            ];
        }else{
            $this->error('类型不存在');
        }
        $order_scanning_code = Db::name("order_scanning_code")
                            ->alias("os")
                            ->join("order o","o.id = os.oid")
                            ->where("os.service_user_id",$param["sid"])
                            ->where($where)
                            ->where(function($query) use ($whereOr){$query->whereOr($whereOr);})
                            ->field("os.id as osid,os.status as osstatus,os.service_user_id,o.id as oid,o.order_no,o.service_time,o.status as ostatus,o.service_gid,o.spec_id,o.address_id,o.create_time,o.type")
                            ->order("o.create_time desc")
                            ->paginate(10)->each(function($item){
                                $service_duration = Db::name('service_duration')->where('id',$item['spec_id'])->find();
                                $service_goods = Db::name('service_goods')->where('id',$item['service_gid'])->field("id,title,zhu_img")->find();
                                if(!empty($service_duration)){
                                    $sku_attribute_list = json_decode($service_duration["specs_list"],true);
                                    $item['spec_data'] = $sku_attribute_list;
                                    $service_goods["price"] = $service_duration["price"];
                                }else{
                                    $order_item = Db::name("order_item")->where("oid",$item["oid"])->find();
                                    $sku_attribute_list = json_decode($order_item["specs_list"],true);
                                    $item['spec_data'] = $sku_attribute_list;
                                    $service_goods["price"] = $order_item["price"];
                                }
                                $item['service_goods'] = $service_goods;
                                $adderss = Db::name("address")->where("id",$item["address_id"])->find();
                                if(!empty($adderss)){
                                    $item['adderss'] = $adderss;
                                }else{
                                    $item['adderss'] = "";
                                }
                                //判断是否有差价订单
                                $flag = Db::name("order_price_difference")->where("oid",$item["oid"])->find();
                                if(empty($flag)){
                                    $item['is_check'] = false;
                                }else{
                                    $item['is_check'] = true;
                                }

                                //判断是否已确认
                                $flag_qew = Db::name("order_scanning_code")->where("oid",$item["oid"])->where("is_confirm",1)->find();
                                if(empty($flag_qew)){
                                    $item['is_confirm'] = false;
                                }else{
                                    $item['is_confirm'] = true;
                                }
                                return $item;
                            });
        $this->success('获取成功',$order_scanning_code);               
    }

    //技师端补交费用创建订单
    public function supplementary_fees(){
        $param = $this->request->param();
        if (empty($param['service_user_id'])) {
            $this->error('技师id不能为空');
        }
        if (empty($param['oid'])) {
            $this->error('订单id不能为空');
        }
        if (empty($param['money'])) {
            $this->error('金额不能为空');
        }
        $order_no = date('Ymd') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . $param['service_user_id'];
        $data = [
            'service_user_id'=>$param['service_user_id'],
            'money'=>$param['money'],
            'oid'=>$param['oid'],
            'sub_order_no'=>$order_no,
            'create_time'=>time(),
        ];
        Db::startTrans();
        try {
            Db::name('order_price_difference')->insert($data); 
            $orderId = Db::name('order_price_difference')->getLastInsID();
        } catch (\Throwable $th) {
            Db::rollback();
            $this->error('补交费用下单失败，请稍后重试');
        }
        Db::commit();
        $this->success('补交费用下单成功，请支付', ['order_no' => $order_no, 'orderId'=>$orderId]);
    }

    //用户端支付补交费用
    public function user_supplementary_pay(){
        $param = $this->request->param();
        if (empty($param['order_no'])) {
            $this->error('未找到指定订单');
        }
        //更新用户id到差价订单表
        Db::name("order_price_difference")->where('sub_order_no', $param['order_no'])->where('status', 0)->update(["uid"=>$this->uid]);
        
        $orderData = DB::name("order_price_difference")->where('sub_order_no', $param['order_no'])->where('status', 0)->where('uid', $this->uid)->find();
        if (empty($orderData)) {
            $this->error('未找到指定订单');
        }
       
        //生成新的支付订单号
        $random_data = $orderData['id'].rand(1,99999).substr(time(),1,2);
        $new_order_no = $param['order_no'].$random_data;
        
        $openid = User::where('id', $orderData['uid'])->value("wx_openid");
       //$openid = "oahPO4mRtWNhE1pRejVcurqOTLMQ";
        $http = is_https() ? 'https' : 'http';
        $notify = $http . '://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER["SERVER_PORT"] . '/api/notify/makeup_notify';
        $wechat = new Pay($this->wechat_config);
        $options = [
            'body' => '订单支付',
            'out_trade_no' => $new_order_no,
            'attach'=>1,//1、正常单第一次支付
            'total_fee' => bcmul($orderData['money'], 100),
            'openid' => $openid,
            'trade_type' => 'JSAPI',
            'notify_url' => $notify,
            'spbill_create_ip' => '127.0.0.1',
        ];
        $result = $wechat->createOrder($options);
        if ($result['return_code'] == "SUCCESS" && $result['return_msg'] == 'OK') {
            $ret = $wechat->createParamsForJsApi($result['prepay_id']);
            $order_record = Db::name('order_record')->where('oid',$orderData['id'])->where('type',1)->find();
            if(empty($order_record)){
                Db::name('order_record')->insert(['oid'=>$orderData['id'],'type'=>1,'order_no'=>$param['order_no'],'random_data'=>$random_data,'new_order_no'=>$new_order_no]);
            }else{
                Db::name('order_record')->where('oid',$orderData['id'])->where('type',1)->update(['order_no'=>$param['order_no'],'random_data'=>$random_data,'new_order_no'=>$new_order_no]);
            }
            $this->success('ok', $ret);
        } else {
            $this->error("支付失败");
        }
    }

    //申请退款
    public function apply_for_refund(){
        $param = $this->request->param();
        if (empty($param['oid'])) {
            $this->error('订单id不能为空');
        }
        $order = Db::name("order")->where("id",$param["oid"])->where("status",2)->find();
        if(empty($order)){
            $this->error('订单不存在');
        }
        Db::name("order")->where("id",$param["oid"])->update(["is_order_refund"=>1,"update_time"=>time()]);
        $this->success("提交成功，请等待管理员审核");
    }

    //技师点击完成服务
    public function technician_completes_service(){
        $param = $this->request->param();
        if (empty($param['oid'])) {
            $this->error('订单id不能为空');
        }
        if (empty($param['service_user_id'])) {
            $this->error('技师id不能为空');
        }
        $flag = Db::name("order_scanning_code")->where("oid",$param["oid"])->where("is_confirm",1)->find();
        if(!empty($flag)){
            $this->error('此订单已确认');
        }
        //判断是否有补交费用订单
        $orfla = Db::name("order_price_difference")->where("oid",$param['oid'])->where("status",0)->find();
        if(!empty($orfla)){
            $this->error('补交金额还未支付，请联系用户支付');
        }
        Db::name("order_scanning_code")->where("oid",$param["oid"])->where("service_user_id",$param['service_user_id'])->where("is_cancel",0)->update(["is_confirm"=>1,"update_time"=>time()]);
        Db::name("order_scanning_code")->where("oid",$param["oid"])->where("is_confirm",0)->where("is_cancel",0)->update(["is_confirm"=>1]);

        //判断用户是否完成了服务
        $order = Db::name("order")->where("id",$param["oid"])->where("status",3)->find();
        if($order["is_complete_service"] == 1){
            Db::name("order")->where("id",$param["oid"])->update(["status"=>4,"completion_time"=>time()]);
            //状态修改成功，给上级和技师返佣
             
            //查询订单技师，更新技师佣金
            $order_scanning_code = Db::name("order_scanning_code")->where("oid",$param["oid"])->where("is_cancel",0)->select()->toArray();
            if(!empty($order_scanning_code)){
                foreach($order_scanning_code as $k=>$v){
                    //查询技师提成比例
                    $service_technician = Db::name("service_technician")->where("id",$v["service_user_id"])->find();
                    $royalty_ratio = bcdiv($service_technician["royalty_ratio"],100,2);
    
                    //更新技师佣金
                    $techn_money = bcmul($order["paidin_money"],$royalty_ratio,2);
                    Db::name("service_technician")->where("id",$v["service_user_id"])->inc("commission",$techn_money)->update();
    
                    //技师佣金记录
                    $ji_data = [
                        "sid"=>$v["service_user_id"],
                        "royalty_ratio"=>$royalty_ratio,
                        "money"=>$techn_money,
                        "uid"=>$order["uid"],
                        "oid"=>$param["oid"],
                        "type"=>1,
                        "desc"=>"订单完成给技师返回佣金",
                        "create_time"=>time()
                    ];
                    Db::name("commission_record")->insert($ji_data);
                }
            }

            //查询分销商比例
            // $distribution_commission_ratio = sysconfig('contact', 'distribution_commission_ratio');
            // $distribution_commission_ratio = bcdiv($distribution_commission_ratio,100,2);

            //更新分销商佣金
            $user = Db::name("user")->where("id",$order["uid"])->find();
            if($user["superior_fid"] > 0){
                //查询分销商等级
                $distributor = Db::name("distributor")->where("id",$user["superior_fid"])->field("id,dis_level")->find();
                //根据分销商等级查出分销商比例
                if($distributor["dis_level"] == 1){
                    $yi_prot = sysconfig('point', 'yi_prot');
                    $grade_proport = bcdiv($yi_prot,100,2);
                }elseif($distributor["dis_level"] == 2){
                    $er_prot = sysconfig('point', 'er_prot');
                    $grade_proport = bcdiv($er_prot,100,2);
                }elseif($distributor["dis_level"] == 3){
                    $san_prot = sysconfig('point', 'san_prot');
                    $grade_proport = bcdiv($san_prot,100,2);
                }elseif($distributor["dis_level"] == 4){
                    $si_prot = sysconfig('point', 'si_prot');
                    $grade_proport = bcdiv($si_prot,100,2);
                }elseif($distributor["dis_level"] == 5){
                    $wu_prot = sysconfig('point', 'wu_prot');
                    $grade_proport = bcdiv($wu_prot,100,2);
                }else{
                    $grade_proport = 0;
                }
                $fxs_money = bcmul($order["paidin_money"],$grade_proport,2);
                Db::name("distributor")->where("id",$user["superior_fid"])->inc("commission",$fxs_money)->update();
                //分销商佣金记录
                $fxs_data = [
                    "superior_fid"=>$user["superior_fid"],
                    "distribution_commission_ratio"=>$grade_proport,
                    "money"=>$fxs_money,
                    "uid"=>$order["uid"],
                    "oid"=>$param["oid"],
                    "desc"=>"订单完成给上级返回佣金",
                    "type"=>2,
                    "create_time"=>time()
                ];
                Db::name("commission_record")->insert($fxs_data);
            }
            
        }

        $this->success("确认成功");
    }

    //用户点击完成服务
    public function user_completes_service(){
        $param = $this->request->param();
        if (empty($param['oid'])) {
            $this->error('订单id不能为空');
        }
        $flag =  Db::name("order")->where("id",$param["oid"])->find();
        if(empty($flag)){
            $this->error('订单不存在');
        }
        //判断是否有补交费用订单
        $orfla = Db::name("order_price_difference")->where("oid",$param['oid'])->where("status",0)->find();
        if(!empty($orfla)){
            $this->error('您有费用未补交，请补交');
        }

        $orderData = Db::name("order")->where("id",$param["oid"])->where("is_complete_service",1)->find();
        $order = Db::name("order")->where("id",$param["oid"])->find();
        if(!empty($orderData)){
            $this->error('此订单已确认');
        }
        Db::name("order")->where("id",$param["oid"])->where("status",3)->update(["is_complete_service"=>1]);

        $order_scanning_code = Db::name("order_scanning_code")->where("oid",$param["oid"])->where("is_cancel",0)->where("is_confirm",1)->select()->toArray();
        if(!empty($order_scanning_code)){
            Db::name("order")->where("id",$param["oid"])->update(["status"=>4,"completion_time"=>time()]);
            //状态修改成功，给上级返佣
            
             //查询订单技师，更新技师佣金
             $order_scanning_code = Db::name("order_scanning_code")->where("oid",$param["oid"])->where("is_cancel",0)->select()->toArray();
             if(!empty($order_scanning_code)){
                 foreach($order_scanning_code as $k=>$v){
                     //查询技师提成比例
                     $service_technician = Db::name("service_technician")->where("id",$v["service_user_id"])->find();
                     $royalty_ratio = bcdiv($service_technician["royalty_ratio"],100,2);
                   
                     //更新技师佣金
                     $techn_money = bcmul($order["paidin_money"],$royalty_ratio,2);
                     Db::name("service_technician")->where("id",$v["service_user_id"])->inc("commission",$techn_money)->update();
     
                     //技师佣金记录
                     $ji_data = [
                         "sid"=>$v["service_user_id"],
                         "royalty_ratio"=>$royalty_ratio,
                         "money"=>$techn_money,
                         "uid"=>$order["uid"],
                         "oid"=>$param["oid"],
                         "type"=>1,
                         "desc"=>"订单完成给技师返回佣金",
                         "create_time"=>time()
                     ];
                     Db::name("commission_record")->insert($ji_data);
                 }
             }
 
             //查询分销比例
            //  $distribution_commission_ratio = sysconfig('contact', 'distribution_commission_ratio');
            //  $distribution_commission_ratio = bcdiv($distribution_commission_ratio,100,2);
 
             //更新分销商佣金
             $user = Db::name("user")->where("id",$order["uid"])->find();
             if($user["superior_fid"] > 0){
                //查询分销商等级
                $distributor = Db::name("distributor")->where("id",$user["superior_fid"])->field("id,dis_level")->find();
                //根据分销商等级查出分销商比例
                if($distributor["dis_level"] == 1){
                    $yi_prot = sysconfig('point', 'yi_prot');
                    $grade_proport = bcdiv($yi_prot,100,2);
                }elseif($distributor["dis_level"] == 2){
                    $er_prot = sysconfig('point', 'er_prot');
                    $grade_proport = bcdiv($er_prot,100,2);
                }elseif($distributor["dis_level"] == 3){
                    $san_prot = sysconfig('point', 'san_prot');
                    $grade_proport = bcdiv($san_prot,100,2);
                }elseif($distributor["dis_level"] == 4){
                    $si_prot = sysconfig('point', 'si_prot');
                    $grade_proport = bcdiv($si_prot,100,2);
                }elseif($distributor["dis_level"] == 5){
                    $wu_prot = sysconfig('point', 'wu_prot');
                    $grade_proport = bcdiv($wu_prot,100,2);
                }else{
                    $grade_proport = 0;
                }
              
                 $fxs_money = bcmul($order["paidin_money"],$grade_proport,2);
                 Db::name("distributor")->where("id",$user["superior_fid"])->inc("commission",$fxs_money)->update();
                 //分销商佣金记录
                 $fxs_data = [
                     "superior_fid"=>$user["superior_fid"],
                     "distribution_commission_ratio"=>$grade_proport,
                     "money"=>$fxs_money,
                     "uid"=>$order["uid"],
                     "oid"=>$param["oid"],
                     "type"=>2,
                     "desc"=>"订单完成给上级返回佣金",
                     "create_time"=>time()
                 ];
                 Db::name("commission_record")->insert($fxs_data);
             }

        }
        $this->success("确认成功");
    }

    //测试定时自动完成服务
    public function rtse(){
        $order = new User();
        $asda = $order->complete_theservice();
        $this->success("确认成功",$asda);
    }

     

    /**
     * 生成海报图片
     * [user_qrcode 参数组合]
     * @param  [type]  $bgImg   [背景图]
     * @param  [type]  $codeImg [二维码]
     * @param  string  $name    [名称]
     * @param  string  $remask  [备注]
     * @param  string  $content [描述]
     * @param  integer $key     [生成二维码名称表示]
     * @return [type]           [description]
     */
    public function generate_poster(){
        $param = $this->request->param();
        if (empty($param['bgImg'])) {
            $this->error('背景图不能为空');
        }
        $bgImg = $param['bgImg'];

        //查询用户二维码
        $user = Db::name("user")->where("id",$this->uid)->find();
        if(empty($user["qrcode"])){
            $this->error('分销二维码不能为空');
        }
        $codeImg= $user["qrcode"];

        //$bgImg = 'static/xcx/15156.jpg';
        //$codeImg='static/xcx/1666688509.png';
        $name="我是".$user["nickname"];
        $remask="邀请您加入隆顺家政 购买有惊喜";
        $content="长按保存二维码图片进入";
 
        $config = array(
          'text'=>array(
            array(
              'text'=>$name,
              'left'=>205,
              'top'=>710,
              'fontPath'=>'static/admin/fonts/simsunb.ttf', //字体文件需要增加去下载引入使用
              'fontSize'=>18,          //字号
              'fontColor'=>'0,0,0',    //字体颜色
              'angle'=>0,
              'text-aligin' => 'left'
            ),
            array(
              'text'=>$remask,
              'left'=>205,
              'top'=>750,
              'fontPath'=>'static/admin/fonts/simsunb.ttf', //字体文件需要增加去下载引入使用
              'fontSize'=>14,             //字号
              'fontColor'=>'143,143,143', //字体颜色
              'angle'=>0,
              'text-aligin' => 'left'
            ),
            array(
              'text'=>'—— '.$content.' ——',
              'left'=>0,
              'right'=>0,
              'top'=>870,
              'fontPath'=>'static/admin/fonts/simsunb.ttf', //字体文件需要增加去下载引入使用
              'fontSize'=>14,             //字号
              'fontColor'=>'169,169,169', //字体颜色
              'angle'=>0,
              'text-aligin' => 'center'   //字体居中，只有center有效果，其他无
            )
          ),
          'image'=>array(
            array(
              'url'=>$codeImg,       //图片资源路径
              'stream'=>0,
                    'left'=>50,
                    'top'=>650,
                    'right'=>0,
                    'bottom'=>0,
                    'width'=>150,
                    'height'=>150,
                    'opacity'=>100
            ),
          ),
          'background'=>$bgImg,
        );
        $filename = "static/xcx/".time().rand(0000,9999).".png";
        return $this->createPoster($config,$filename);
    }
 
 
    /**
     * 生成宣传海报
     * @param  array    参数,包括图片和文字
     * @param  string   $filename 生成海报文件名,不传此参数则不生成文件,直接输出图片
     * @return [type] [description]
     */
    public function createPoster($config=array(),$filename=""){
        //如果要看报什么错，可以先注释调这个header 
        if(empty($filename)) header("content-type: image/png");
            $imageDefault = array(
                'left'=>0,
                'top'=>0,
                'right'=>0,
                'bottom'=>0,
                'width'=>100,
                'height'=>100,
                'opacity'=>100
            );
            $textDefault =  array(
                'text'=>'',
                'left'=>0,
                'top'=>0,
                'fontSize'=>32,             //字号
                'fontColor'=>'255,255,255', //字体颜色
                'angle'=>0,
            );
        $background = $config['background'];//海报最底层得背景  
        //背景方法
        $backgroundInfo = getimagesize($background);
        $backgroundFun = 'imagecreatefrom'.image_type_to_extension($backgroundInfo[2], false);
        $background = $backgroundFun($background);
     
        $backgroundWidth = imagesx($background);    //背景宽度
        $backgroundHeight = imagesy($background) + 300;   //背景高度，这里增加300的高度，底部白色区域
     
        $imageRes = imageCreatetruecolor($backgroundWidth,$backgroundHeight); 
        $color = imagecolorallocate($imageRes, 255, 255, 255);  
        imagefill($imageRes, 0, 0, $color);  
        // imageColorTransparent($imageRes, $color);    //颜色透明
        imagecopyresampled($imageRes,$background,0,0,0,0,imagesx($background),imagesy($background),imagesx($background),imagesy($background));
        //处理了图片
        if(!empty($config['image'])){
            foreach ($config['image'] as $key => $val) {
                $val = array_merge($imageDefault,$val); 
                $info = getimagesize($val['url']);
                $function = 'imagecreatefrom'.image_type_to_extension($info[2], false);
                if($val['stream']){     //如果传的是字符串图像流
                    $info = getimagesizefromstring($val['url']);
                    $function = 'imagecreatefromstring';
                }
                $res = $function($val['url']);
                $resWidth = $info[0];
                $resHeight = $info[1];
                //建立画板 ，缩放图片至指定尺寸
                $canvas=imagecreatetruecolor($val['width'], $val['height']); 
                imagefill($canvas, 0, 0, $color);
                //关键函数，参数（目标资源，源，目标资源的开始坐标x,y, 源资源的开始坐标x,y,目标资源的宽高w,h,源资源的宽高w,h） 
                imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'],$resWidth,$resHeight); 
                $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']) - $val['width']:$val['left'];
                $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']) - $val['height']:$val['top'];
                //放置图像
                imagecopymerge($imageRes,$canvas, $val['left'],$val['top'],$val['right'],$val['bottom'],$val['width'],$val['height'],$val['opacity']);//左，上，右，下，宽度，高度，透明度 
            }
        }
       
        //处理文字
        if(!empty($config['text'])){
            foreach ($config['text'] as $key => $val) {
                $val = array_merge($textDefault,$val);
                list($R,$G,$B) = explode(',', $val['fontColor']);
                $fontColor = imagecolorallocate($imageRes, $R, $G, $B); 
                if($val['text-aligin'] == 'center'){
                    $fontBox = imagettfbbox($val['fontSize'], 0, $val['fontPath'], $val['text']);//获取文字所需的尺寸大小
                    //垂直水平居中
                    //imagettftext($imageRes, $val['fontSize'], $val['angle'], ceil(($backgroundWidth - $fontBox[2]) / 2), ceil(($backgroundHeight - $fontBox[1] - $fontBox[7]) / 2), $fontColor, $val['fontPath'], $val['text']);
                    //水平居中
                    imagettftext($imageRes, $val['fontSize'], $val['angle'], ceil(($backgroundWidth - $fontBox[2]) / 2), $val['top'], $fontColor, $val['fontPath'], $val['text']);
                    //  imagettftext($imageRes, $val['fontSize'], $val['angle'], ceil(($backgroundWidth - $fontBox[2]) / 2), $val['top'], $fontColor,  '',$val['text']);
                }else{
                    $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']):$val['left'];
                    $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']):$val['top'];
                    imagettftext($imageRes,$val['fontSize'],$val['angle'],$val['left'],$val['top'],$fontColor,$val['fontPath'],$val['text']);
                }
            }
        }   
        $domain = ($this->isHTTPS() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST']; //获取域名
        //生成图片  
        if(!empty($filename)){
            // ROOT_PATH
            $res = imagepng($imageRes,$filename); //保存到本地
            imagedestroy($imageRes);
            if(!$res) return false;
            $save_path =$domain.'/' .$filename;
            $this->success("生成成功",$save_path);
        }else{
            imagepng ($imageRes);//在浏览器上显示
            imagedestroy($imageRes);
        }
        $save_path =$domain.'/' .$imageRes;
        $this->success("生成成功",$save_path);
    }

    //我的优惠券
    public function my_coupon_list(){
        $param = $this->request->post();
        if(empty($param["type"])){
            $this->error("类型不能为空");
        }
       
        Db::name("coupon_user")->where("uid",$this->uid)
            ->where("status",$param["type"])
            ->paginate(10)->each(function($item){
                $time = date("Y-m-d H:i:s",time());
                $coupon = Db::name("coupon")->where("id",$item["coupon_id"])->field("endtime,title,full_amount,less_amount")->find();
                if($coupon["endtime"] < $time){
                    Db::name("coupon_user")->where("id",$item["id"])->update(["status"=>3]);
                }
            });
        $list = Db::name("coupon_user")->where("uid",$this->uid)
            ->where("status",$param["type"])
            ->paginate(10)->each(function($item){
                $coupon = Db::name("coupon")->where("id",$item["coupon_id"])->field("endtime,title,full_amount,less_amount")->find();
                $item["coupon_endtime"] = $coupon["endtime"];
                $item["title"] = $coupon["title"];
                $item["full_amount"] = $coupon["full_amount"];
                $item["less_amount"] = $coupon["less_amount"];
                return $item;
            });
      
        $this->success('获取成功',$list);
    }

    //技师扫码
    public function technician_scanning_code(){
        $param = $this->request->post();
        if(empty($param["oid"])){
            $this->error("订单id不能为空");
        }
        if(empty($param["sid"])){
            $this->error("技师id不能为空");
        }
        $order = Db::name("order")->where("id",$param["oid"])->where("status",2)->find();
        if(empty($order)){
            $this->error("此订单不能扫码");
        }
        $flag = Db::name("order_scanning_code")->where("oid",$param["oid"])->where("service_user_id",$param["sid"])->find();
        if(empty($flag)){
            $this->error("此订单没有给您分配,不能扫码");
        }

        $asfv = Db::name("order_scanning_code")->where("oid",$param["oid"])->where("service_user_id",$param["sid"])->where("status",1)->find();
        if(!empty($asfv)){
            $this->error('此订单已扫码');
        }

        Db::name("order_scanning_code")->where("oid",$param["oid"])->where("service_user_id",$param['sid'])->update(["type"=>1,"status"=>1]);
        Db::name("order_scanning_code")->where("oid",$param["oid"])->where("status",0)->update(["status"=>1]);
        Db::name("order")->where("id",$param["oid"])->update(["status"=>3]);
        $this->success("核销成功");

    }

    //取消退款
    public function order_cancel_refund(){
        $param = $this->request->post();
        if(empty($param["oid"])){
            $this->error("订单id不能为空");
        }
        $order = Db::name("order")->where("id",$param["oid"])->where("status",6)->find();
        if(empty($order)){
            $this->error("此订单不能取消退款");
        }
        Db::name("order")->where("id",$param["oid"])->update(["status"=>2,"is_order_refund"=>0]);
        $this->success("取消成功");
    }
 
    
  

  
   

}
